<template>
  <div>
    <!--  顶部面包屑  -->
    <div class="ccui-navigation">
      <el-button
        size="mini"
        type="primary-icon-medium"
        icon="icon-ccui-return"
        @click="handleBack"
        >返回</el-button
      >
      <div class="ccui-navigation-divider" />
      <!-- 面包屑 -->
      <el-breadcrumb
        class="ccui-navigation-crumbs-container"
        separator-class="el-icon-arrow-right"
      >
        <el-breadcrumb-item
          :to="{ path: $store.getters.getBreadcrumb('level1').path }"
          >{{ $store.getters.getBreadcrumb("level1").name }}</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: '/inventoryManagement' }"
          >库存管理(财务)</el-breadcrumb-item
        >
        <el-breadcrumb-item
          :to="{
            path: '/inventoryManagement/transferFinanceWarehousing/whole'
          }"
          >运输财务入库管理</el-breadcrumb-item
        >
        <el-breadcrumb-item :to="{ path: toUrl }">{{
          pathName
        }}</el-breadcrumb-item>
        <el-breadcrumb-item>
          <span class="ccui-curr-crumb">新增</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="ccui-app-container-detail">
      <div class="ccui-app-container-detail-body">
        <el-tabs
          v-model="activeName"
          @tab-click="handleClick"
          class="el-tabs__customize"
        >
          <el-tab-pane label="基本信息" name="first">
            <basicInformation
              ref="formDateBUI"
              :storageList="storageList"
              :storageForm="storageForm"
              @updataList="updataList"
              @association="association"
              @getAssociationList="getAssociationList"
            ></basicInformation>
          </el-tab-pane>
          <el-tab-pane label="采购清单" name="second">
            <contractList
              ref="contractList"
              :storage-list="storageList"
              :storageForm="storageForm"
              @delectList="delectList"
              :priceFillingMethodType="priceFillingMethodType"
            ></contractList>
          </el-tab-pane>
          <el-tab-pane label="关联入库单" name="third" v-if="isHideAssociation">
            <associationWarehousing
              ref="association"
              :storage-list="associationList"
            ></associationWarehousing>
          </el-tab-pane>
          <el-tab-pane label="附件" name="fourth">
            <upload-info
              ref="contractAppendix"
              isTab
              v-model="fileList"
              title="合同附件"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!--  按钮  -->
    <el-bottom-guide>
      <ul class="ccui-bottom-button">
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="tsSaveTranStorage"
            >暂存</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-save"
            @click="submitHandle('save')"
            >保存并校验</el-button
          >
        </li>
        <li>
          <el-button
            type="bottom"
            icon="icon-ccui-cancel"
            @click="submitHandle('submit')"
            >保存并提交</el-button
          >
        </li>
        <div class="ccui-bottom-guide-divider" />
        <li>
          <el-button type="bottom" icon="icon-ccui-return" @click="resetHandle"
            >返回</el-button
          >
        </li>
      </ul>
    </el-bottom-guide>
  </div>
</template>

<script>
import basicInformation from "./add/basicInformation";
import UploadInfo from "@/basa/components/public/uploadInfo2";
import contractList from "./add/contractList";
import associationWarehousing from "./add/association-warehousing.vue";
import {
  tsSaveTranStorage,
  saveFinStorage,
  submitFinStorage
} from "../api/add-item";
import { ishasAgentId } from "@/basa/utils";
import peopleManage from "../mixins/peopleManage";
export default {
  name: "new-item",
  mixins: [peopleManage],
  components: {
    basicInformation,
    associationWarehousing,
    contractList,
    UploadInfo
  },
  data() {
    return {
      storageForm: {
        settlementCount: 0,
        moneyWithTax: 0
      },
      storageList: [],
      activeName: "first",
      submitFlag: false,
      priceFillingMethodType: "",
      focus: "formDateBUI",
      fileList: [], // 附件上传id集合
      contractListBool: false, //变更更明细是否为空
      isHideAssociation: true, //控制影藏关联入库单页签
      associationList: [], //关联入库单数据列表
      messageCount: ""
    };
  },
  methods: {
    updataList(val) {
      this.storageList = val;
    },
    delectList(val) {
      this.storageList = val.filter((item) => item.check != true);
    },
    handleClick(tab, event) {
      this.activeName = tab.name;
    },
    association(val) {
      this.isHideAssociation = val;
    },
    getAssociationList(data) {
      this.associationList = data;
    },
    // 暂存
    tsSaveTranStorage() {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach((row) => {
        row.fileInfoId = row.uploadId;
        row.createTime = new Date(row.createTime).getTime();
        row.uploadTime = new Date(row.createTime).getTime();
      });
      let storageList = this.storageList;
      storageList.forEach((item) => {
        item.storageCount = item.storageCount ? item.storageCount : "0.000";
      });

      let associationList = this.associationList;
      associationList.forEach((item) => {
        item.storageId = item.id;
        item.tranStorageType = item.storageType;
      });

      let obj = {
        tranStorageBO: this.$refs.formDateBUI.form,
        fileBOList: fileList1,
        tranStorageListBOList: storageList,
        tranStorageRelBOList: associationList
      };

      //对下计价
      if (obj.tranStorageBO.finType == "1") {
        obj.tranStorageBO.refStorageCodeString = "";
        obj.tranStorageBO.refStorageIdString = "";
        obj.tranStorageBO.warehouseName = "";
        obj.tranStorageBO.warehouseCode = "";
        obj.tranStorageBO.warehouseId = "";
        //运输产品分类 固定存取选择结算单后的物资三级分类名称
        obj.tranStorageBO.thirdCategoriesOfName =
          obj.tranStorageBO.thirdCategoriesOfName1;

        obj.tranStorageRelBOList = [];
      }
      obj.tranStorageBO.storageType = parseInt(
        sessionStorage.getItem("storageType")
      );
      this.$loading({
        lock: true,
        text: "暂存中,请稍后...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      tsSaveTranStorage(obj)
        .then((res) => {
          this.$loading().close();
          let { code } = res.data;
          this.$message({
            message: "暂存成功",
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
        })
        .catch((e) => {
          this.$loading().close();
          console.log(e);
        });
    },
    // 保存 提交
    submitHandle(name) {
      this.getValidate(this.storageList);
      this.$refs.formDateBUI.$refs.form.validate((valid) => {
        console.log(valid, "validvalid");
        if (valid) {
          if (this.contractListBool) {
            // 调接口
            if (name == "save") {
              this.saveFinStorage();
            } else {
              this.submitFinStorage();
            }
          } else {
            // 弹个窗
            this.$message({
              type: "error",
              message: this.messageCount,
              showClose: true,
              ccuiCustom: true
            });
            this.activeName = "second";
          }
        } else {
          this.$showErrorMessage("入库单基本信息不完整，请编辑后保存");
          this.activeName = "first";
        }
      });
    },
    saveFinStorage(name) {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach((row) => {
        row.fileInfoId = row.uploadId;
        row.createTime = new Date(row.createTime).getTime();
        row.uploadTime = new Date(row.createTime).getTime();
      });
      let storageList = this.storageList;
      storageList.forEach((item) => {
        item.storageCount = item.storageCount ? item.storageCount : "0.000";
      });

      let associationList = this.associationList;
      associationList.forEach((item) => {
        item.storageId = item.id;
        item.tranStorageType = item.storageType;
      });

      let obj = {
        tranStorageBO: this.$refs.formDateBUI.form,
        fileBOList: fileList1,
        tranStorageListBOList: storageList,
        tranStorageRelBOList: associationList
      };

      //对下计价
      if (obj.tranStorageBO.finType == "1") {
        obj.tranStorageBO.refStorageCodeString = "";
        obj.tranStorageBO.refStorageIdString = "";
        obj.tranStorageBO.warehouseName = "";
        obj.tranStorageBO.warehouseCode = "";
        obj.tranStorageBO.warehouseId = "";
        //运输产品分类 固定存取选择结算单后的物资三级分类名称
        obj.tranStorageBO.thirdCategoriesOfName =
          obj.tranStorageBO.thirdCategoriesOfName1;

        obj.tranStorageRelBOList = [];
      }
      obj.tranStorageBO.storageType = parseInt(
        sessionStorage.getItem("storageType")
      );
      saveFinStorage(obj)
        .then((res) => {
          let { code, message } = res.data;
          this.$message({
            message: message,
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
          console.log(res, "保存");
        })
        .catch((e) => {
          console.log(e);
        });
    },
    submitFinStorage(name) {
      let fileList1 = JSON.parse(JSON.stringify(this.fileList));
      fileList1.forEach((row) => {
        row.fileInfoId = row.uploadId;
        row.createTime = new Date(row.createTime).getTime();
        row.uploadTime = new Date(row.createTime).getTime();
      });
      let storageList = this.storageList;
      storageList.forEach((item) => {
        item.storageCount = item.storageCount ? item.storageCount : "0.000";
      });

      let associationList = this.associationList;
      associationList.forEach((item) => {
        item.storageId = item.id;
        item.tranStorageType = item.storageType;
      });

      let obj = {
        tranStorageBO: this.$refs.formDateBUI.form,
        fileBOList: fileList1,
        tranStorageListBOList: storageList,
        tranStorageRelBOList: associationList
      };

      //对下计价
      if (obj.tranStorageBO.finType == "1") {
        obj.tranStorageBO.refStorageCodeString = "";
        obj.tranStorageBO.refStorageIdString = "";
        obj.tranStorageBO.warehouseName = "";
        obj.tranStorageBO.warehouseCode = "";
        obj.tranStorageBO.warehouseId = "";
        //运输产品分类 固定存取选择结算单后的物资三级分类名称
        obj.tranStorageBO.thirdCategoriesOfName =
          obj.tranStorageBO.thirdCategoriesOfName1;

        obj.tranStorageRelBOList = [];
      }

      obj.tranStorageBO.storageType = parseInt(
        sessionStorage.getItem("storageType")
      );
      submitFinStorage(obj)
        .then((res) => {
          let { code, message } = res.data;
          this.$message({
            message: message,
            type: code === "0" ? "success" : "error",
            showClose: true,
            ccuiCustom: true
          });
          if (code === "0") {
            this.submitFlag = true;
            this.handleBack();
          }
          console.log(res, "提交");
        })
        .catch((e) => {
          console.log(e);
        });
    },
    // 校验采购请单关联入库单列表不能为空
    getValidate(data) {
      let newArr = data.filter((item) => item.relationList);
      let newArrTow = newArr.filter((item) => !item.relationList.length);
      let a = [];
      newArrTow.forEach((item) => {
        if (item.materialCode == "") {
          return a.push(item.materialName);
        } else if (item.materialCode && item.materialCode != "") {
          return (this.messageCount =
            "设备物资编码" + item.materialCode + ",请关联入库单");
        }
      });
      if (a.length > 0) {
        this.messageCount = a.join(",请关联入库单; ") + ",请关联入库单;";
      }
      this.contractListBool = newArr.every((item) => {
        return item.relationList.length;
      });
    },
    // 取消
    resetHandle() {
      this.handleBack();
    },
    // 获取价格填写方式
    gatPriceFillingMethod(item) {
      console.log("0=含税价、1=不含税价", item);
      this.priceFillingMethodType = item;
    },
    summaryMoney(val) {
      console.log(val, " ");
      this.summaryMoneyArr = val;
    },
    handleBack() {
      this.$router.go(-1);
      this.$refs.formDateBUI.$refs.form.clearValidate();
      this.$refs.formDateBUI.$refs.form.resetFields();
      // this.$refs.attachment.form.fileArr = [];
      // this.$refs.attachment.tableData = [];
      this.$refs.contractList.tableData = [];
      this.$refs.contractList.concChangesDel = [];
    },
    tabChange(item, index) {
      this.focus = item[0];
      this.$refs[item[0]].$el.scrollIntoView({
        behavior: "smooth", // 平滑过渡
        block: "start" // 上边框与视窗顶部平齐。默认值
      });
    }
  },
  beforeRouteEnter(to, from, next) {
    console.log(to, "lookMe");
    !(to.fullPath === from.fullPath) &&
      sessionStorage.setItem("fromPath", from.fullPath);
    if (from.name == "transport-inventory-financialList-whole") {
      sessionStorage.setItem("storageType", 0);
    } else if (from.name == "transport-inventory-financeWarehousing-whole") {
      sessionStorage.setItem("storageType", 1);
    }
    next();
  },
  // 更改列表缓存状态
  beforeRouteLeave(to, from, next) {
    if (this.submitFlag === true) {
      for (var key in this.$vnode.parent.parent.componentInstance.cache) {
        delete this.$vnode.parent.parent.componentInstance.cache[
          ishasAgentId(to.path, key)
        ];
      }
    }
    next();
  }
};
</script>

<style lang="scss" scoped>
/deep/ .file-group .el-group-title .group-content {
  margin-top: 40px;
}

/deep/ .el-group-title.ccui-group-wrapper .extend-btn {
  top: 0;
}

.detail-info {
  width: calc(100% - 438px);
  min-height: calc(100vh - 260px);
  float: left;
  background: #fff;
  position: relative;
  padding: 14px 20px 0 20px;
  margin: 15px 0 80px;
}
/deep/.el-table td,
.el-table th {
  padding: 0 0;
  height: 36px;
}
/deep/.el-col-13 {
  width: 79%;
}

/deep/.detail-info-el-Label {
  position: absolute;
  width: 107px;
  right: 50px;
  top: 31px;
  z-index: 1;
}

.el-none {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  white-space: normal;
  word-break: break-all;
  word-wrap: break-word;
}
/deep/.extend-btn {
  text-align: right;
  margin-bottom: 15px;
  top: 0px;
  position: relative !important;
}
/deep/.ccui-form {
  margin-top: 0px;
}
/deep/ .ccui-multifunctional-table-wrapper {
  .el-table td,
  .el-table th.is-leaf {
    border-right: 1px solid #edf2fc;
  }
}
/deep/ .el-table__footer-wrapper {
  margin-top: 0px;
}
// 表格合计行样式
/deep/.el-table__footer {
  width: 100% !important;
}

// 解决表格定位滚动条无法拖动
/deep/ .el-table__fixed-header-wrapper {
  th {
    pointer-events: auto;
  }
}
/deep/ .el-table__fixed,
/deep/.el-table__fixed-right {
  pointer-events: none;
  td {
    pointer-events: auto;
  }
}
/deep/.el-table--border {
  th:last-of-type.gutter {
    display: table-cell !important;
    width: 0px !important;
  }
}

/deep/
  .ccui-multifunctional-table-wrapper
  .el-table
  tbody
  tr
  td:last-child
  .cell {
  padding-right: 5px !important;
}
</style>
